package org.hackystat.projectbrowser.page.chooseTAP;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.hackystat.ambientdevice.server.jaxb.Project;
import org.hackystat.ambientdevice.server.jaxb.TriggerActionPair;
import org.hackystat.ambientdevice.server.jaxb.Project.TriggerActionPairs;
import org.hackystat.projectbrowser.ProjectBrowserSession;
import org.hackystat.projectbrowser.page.settrigger.ChooseTrigger;

/**
 * The class that creates a new trigger/action pair
 * @author Edward Kim
 *
 */
public class NewTAPForm extends StatelessForm {

  /** Supports serialization. */
  private static final long serialVersionUID = 1L;

  private String tempTAP;
  private String projectName;
  private PageParameters responseParam = new PageParameters();

  /**
   * The form that creates a new trigger/action pair.
   * @param id The id that is passed to the super class (not really needed).
   * @param projectName The name of the current project. 
   */
  public NewTAPForm(String id, String projectName) {
    super(id);

    this.projectName = projectName;
    responseParam.add("projectName", this.projectName);

    setModel(new CompoundPropertyModel(this));
    add(new TextField("tempTAP"));
  }

  /**
   * When the form is submiting, check for errors and try to create a new project.
   */
  @Override
  public void onSubmit() {
    TriggerActionPair newTap = new TriggerActionPair();
    Project tempProject = ProjectBrowserSession.get().getProjectTypeXMLByNameId(projectName);

    if (tempProject.isSetTriggerActionPairs()) {
      newTap.setId(tempTAP);
      tempProject.getTriggerActionPairs().getTriggerActionPair().add(newTap);
    }

    else {
      newTap.setId(tempTAP);
      TriggerActionPairs newTAPS = new TriggerActionPairs();
      newTAPS.getTriggerActionPair().add(newTap);
      tempProject.setTriggerActionPairs(newTAPS);
    }
    //set response page to go back to chooseTAP
    responseParam.add("tapName", tempTAP);
    setResponsePage(ChooseTrigger.class, responseParam);
  }

  /**
   * The setter for tempTAP.
   * @param tempTAP The tempTAP to be set.
   */
  public void setTempTAP(String tempTAP) {
    this.tempTAP = tempTAP;
  }

  /**
   * The getter for tempTAP.
   * @return returns tempTAP.
   */
  public String getTempTAP() {
    return tempTAP;
  }

}
